package com.wlj.security.app;

import com.wlj.security.app.authentication.openid.OpenIdAuthenticationSecurityConfig;
import com.wlj.security.core.authentication.sms.SmsAuthenticationSecurityConfig;
import com.wlj.security.core.authorize.AuthorizeConfigManager;
import com.wlj.security.core.properties.SecurityConstants;
import com.wlj.security.core.validate.code.config.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.social.security.SpringSocialConfigurer;

//资源服务器
@Configuration
@EnableResourceServer
public class AppResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 访问自己的api接口需要加上access_token
     * 在请求头里加上: Authorization = (token_type)bearer (access_token)c4232a0d-d538-42e0-ba0a-3e67bb1388a9
     */


    /**
     * 配置SocialAuthenticationFilter生效
     */
    @Autowired
    private SpringSocialConfigurer wljSocialSecurityConfig;

    @Autowired
    private OpenIdAuthenticationSecurityConfig openIdAuthenticationSecurityConfig;

    @Autowired
    private SmsAuthenticationSecurityConfig smsAuthenticationSecurityConfig;

    @Autowired
    private AuthenticationSuccessHandler wljAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler wljAuthenticationFailureHandler;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    @Autowired
    private AuthorizeConfigManager authorizeConfigManager;


    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage(SecurityConstants.DEFAULT_LOGIN_PAGE_URL)
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
                .successHandler(wljAuthenticationSuccessHandler)
                .failureHandler(wljAuthenticationFailureHandler);

        http.apply(validateCodeSecurityConfig)
                .and()
                .apply(smsAuthenticationSecurityConfig)
                .and()
                .apply(wljSocialSecurityConfig)
                .and()
                .apply(openIdAuthenticationSecurityConfig)
                .and()
                .csrf().disable();  //停止跨站请求伪造的防护功能
        authorizeConfigManager.config(http.authorizeRequests());
    }
}
